package com.zhb.cloud.controller;

import java.io.IOException;
import java.util.Date;
import java.util.concurrent.ExecutionException;

import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.rest.RestStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static org.elasticsearch.common.xcontent.XContentFactory.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhb.cloud.model.Article;

@RestController
@RequestMapping("article")
public class ArticleController {
	private Logger logger = LoggerFactory.getLogger(ArticleController.class);
	@Autowired
	private TransportClient transportClient;

	/**
	 * @Title: AddIndex
	 * @author: zhb
	 * @date: 2017年7月27日 下午10:37:21
	 * @Description: 创建一个新的es库以及对应的表
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("addIndex")
	public String AddIndex() throws IOException {
		IndexRequestBuilder prepareIndex = transportClient.prepareIndex("articles", "article");
		/**
		 * 使用es的拼接方式
		 */
		XContentBuilder xContentBuilder = jsonBuilder().startObject().field("author", "保尔柯察金")
				.field("publishTime", new Date()).field("title", "钢铁是怎么样练成的").endObject();
		/**
		 * 采用json的形式
		 */
		prepareIndex.setSource(xContentBuilder);
		IndexResponse indexResponse = prepareIndex.get();
		// Index name 数据库名称
		String _index = indexResponse.getIndex();
		logger.info("数据库名称:" + _index);
		// Type name 表的名称
		String _type = indexResponse.getType();
		logger.info("表的名称" + _type);
		// Document ID (generated or not)
		String _id = indexResponse.getId();
		logger.info("唯一ID" + _id);
		// Version 版本,如果是第一次创建则为1
		long _version = indexResponse.getVersion();
		logger.info("版本" + _version);
		// status has stored current instance statement.
		RestStatus status = indexResponse.status();
		logger.info("状态 :" + status);
		logger.info("创建成功!!!");
		return "成功";
	}

	/**
	 * @Title: deleteIndex
	 * @author: zhb
	 * @date: 2017年7月28日 上午11:28:39
	 * @Description: 删除
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("deleteIndex")
	public String deleteIndex() throws IOException {
		String id = "AV2HL3TqsIm9e1lGVhrV";
		// 根据ID删除
		DeleteResponse deleteResponse = transportClient.prepareDelete("articles", "article", id).get();
		String type = deleteResponse.getType();
		logger.info(type);
		return "成功";
	}

	/**
	 * @Title: getIndex
	 * @author: zhb
	 * @date: 2017年7月28日 上午11:25:48
	 * @Description: 查询
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("getIndex")
	public String getIndex() throws IOException {
		// 查询所有
		// GetResponse getResponse = transportClient.prepareGet().get();
		// String string = getResponse.getSourceAsString();
		// 在知道id的情况下使用
		String id = "AV2HL3TqsIm9e1lGVhrV";
		GetResponse getResponse = transportClient.prepareGet("articles", "article", id).get();
		logger.info(getResponse.getSourceAsString());
		return "成功";
	}

	/**
	 * @Title: update
	 * @author: zhb
	 * @date: 2017年7月28日 下午12:03:13
	 * @Description: 更新操作方式一
	 * @return
	 * @throws IOException
	 * @throws ExecutionException
	 * @throws InterruptedException
	 */
	@RequestMapping("update")
	public String update() throws IOException, InterruptedException, ExecutionException {
		// 根据脚本更新
		// UpdateRequest updateRequest1 = new UpdateRequest("ttl", "doc",
		// "1").script(new Script("ctx._source.gender = \"male\"")));
		// transportClient.update(updateRequest1).get();

		String id = "AV2HL3TqsIm9e1lGVhrV";
		UpdateRequest updateRequest = new UpdateRequest();
		updateRequest.index("articles");
		updateRequest.type("article");
		updateRequest.id(id);
		updateRequest.doc(jsonBuilder().startObject().field("author", "张三丰").endObject());
		UpdateResponse updateResponse = transportClient.update(updateRequest).get();
		logger.info(updateResponse.getId());
		return "成功";
	}

	/**
	 * @Title: updateIndex
	 * @author: zhb
	 * @date: 2017年7月28日 下午12:03:13
	 * @Description: 更新操作方式二
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("updateIndex")
	public String updateIndex() throws IOException {
		// 根据脚本scripts更新
		// transportClient.prepareUpdate("ttl", "doc", "1").setScript(new
		// Script("ctx._source.gender = \"male\"")).get();

		String id = "AV2HL3TqsIm9e1lGVhrV";
		UpdateResponse updateResponse = transportClient.prepareUpdate("articles", "article", id)
				.setDoc(jsonBuilder().startObject().field("author", "李白").endObject()).get();
		// 在知道id的情况下使用
		logger.info(updateResponse.getId());
		return "成功";
	}

	/**
	 * @Title: updateMerger
	 * @author: zhb
	 * @date: 2017年7月28日 下午12:03:13
	 * @Description: 更新操作方式三 合并文档,将其添加达到文档中
	 * @return
	 * @throws IOException
	 * @throws Exception
	 * @throws InterruptedException
	 */
	@RequestMapping("updateMerger")
	public String updateMerger() throws IOException, InterruptedException, Exception {
		String id = "AV2HL3TqsIm9e1lGVhrV";
		UpdateRequest updateRequest = new UpdateRequest("articles", "article", id)
				.doc(jsonBuilder().startObject().field("company", "你猜猜").endObject());
		UpdateResponse updateResponse = transportClient.update(updateRequest).get();
		logger.info(updateResponse.getId());
		return "成功";
	}

	/**
	 * @Title: savaOrUpdate
	 * @author: zhb
	 * @date: 2017年7月28日 下午12:21:30
	 * @Description: saveOrUpdate
	 * @return
	 * @throws IOException
	 * @throws InterruptedException
	 * @throws Exception
	 */
	@RequestMapping("savaOrUpdate")
	public String savaOrUpdate() throws IOException, InterruptedException, Exception {
		String id = "sdsfdsfdsafads";
		IndexRequest indexRequest = new IndexRequest("articles", "article", id).source(jsonBuilder().startObject()
				.field("publishTime", new Date()).field("author", "韩信").field("title", "三连击").endObject());
		UpdateRequest updateRequest = new UpdateRequest("index", "type", "1")
				.doc(jsonBuilder().startObject().field("company", "汉朝").endObject()).upsert(indexRequest);
		transportClient.update(updateRequest).get();
		return "成功";
	}

	public static byte[] toJson() throws JsonProcessingException {
		ObjectMapper objectMapper = new ObjectMapper();
		Article article = new Article();
		article.setAuthor("朱宏斌");
		article.setPublishTime("2015-09-09");
		article.setTitle("钢铁是怎样炼成的");
		return objectMapper.writeValueAsBytes(article);
	}

}
